﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using App.Core.Extensions;
using App.Domain;
using App.Web.ViewModels;
using App.Web.Utility;
using AutoMapper;
using System.Text;

namespace App.Web.Areas.Admin.Controllers
{
    public class UtilityController : BaseController
    {
		private AppEntities _Context = new AppEntities();
        
		#region Constructors
		public UtilityController()
		{
		}

		public UtilityController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public String SendFailedEmail()
        {            
            var query = from P in _Context.EmailMessages where !P.IsSent select P;
            int successCount = 0;
            int failedCount = 0;
            StringBuilder errors = new StringBuilder(10);
            List<EmailMessage> messages = query == null || query.Count() == 0 ? new List<EmailMessage>() : query.ToList();
            foreach (EmailMessage message in messages)
            {
                try
                {
                    message.AttemptedOn = DateTime.Now;
                    App.Core.Mail.MailManager.SendMail(message.ToEmail, message.CC, message.BCC, message.FromEmail, message.Subject, message.Message);
                    message.IsSent = true;
                    successCount++;
                }
                catch (Exception ex)
                {
                    errors.AppendFormat("{0}<br/><br/>", ex.Message);
                    //lblMessage.Text = ex.Message;
                    //lblMessage.Text += "<br/>" + ex.StackTrace;

                    //break;
                    failedCount++;
                }
            }
            _Context.SaveChanges();
            //if (errors.Length > 0)
            //    lblMessage.Text = errors.ToString();

            //lblMessage.Text += String.Format("Total {0} emails sent and {1} failed", successCount, failedCount);

            var result = new
            {
                SuccussMessage = String.Format("Total {0} emails sent and {1} failed", successCount, failedCount),
                ErrorMessage = String.Format("<div class='{0}'>{1}</div>", AppConstants.UI.ERROR_MESSAGE_CLASS, errors.ToString())
            };
            return result.ToJSON();            
        }
		#endregion Action Methods
		
		#region Helper Methods

        #endregion			
    }
}
